package elitech.vietnam.myfashion;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Category;
import elitech.vietnam.myfashion.entites.City;
import elitech.vietnam.myfashion.entites.District;
import elitech.vietnam.myfashion.entites.Member;
import elitech.vietnam.myfashion.entites.Notify;
import elitech.vietnam.myfashion.entites.Order;
import elitech.vietnam.myfashion.entites.OrderDetail;
import elitech.vietnam.myfashion.entites.Post;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.extend.ViewPagerAdapter;
import elitech.vietnam.myfashion.fragment.DetailFragment;
import elitech.vietnam.myfashion.fragment.EditProfileFragment;
import elitech.vietnam.myfashion.fragment.FollowListFragment;
import elitech.vietnam.myfashion.fragment.MainPageViewFragment;
import elitech.vietnam.myfashion.fragment.MemberStyleFragment;
import elitech.vietnam.myfashion.fragment.ProductFragment;
import elitech.vietnam.myfashion.fragment.StylerFragment;
import elitech.vietnam.myfashion.gcm.GCMIntentService;
import elitech.vietnam.myfashion.view.EditProfileView;
import elitech.vietnam.myfashion.view.MainPageView;
import elitech.vietnam.myfashion.view.MyShoppingView;
import elitech.vietnam.myfashion.view.MyStyleView;
import elitech.vietnam.myfashion.wsclient.Utilities;
import eu.janmuller.android.simplecropimage.CropImage;

public class MainActivity extends FragmentActivity implements OnClickListener {

	public static final String IMAGE_TEMP = Environment.getExternalStorageDirectory() + "/ShoppingTemp.jpg";
	public static final int LOGINACTIVITY = 1;
	public static final int CAMERA_MYSTYLE = 2;
	public static final int LIBRAR_MYSTYLE = 3;
	public static final int CAMERA_SETTING = 4;
	public static final int LIBRAR_SETTING = 5;
	public static final int CROP_FROM_CAMERA = 6;
	public static final int CROP_EDIT_PROFILE = 7;

	public static final String GCM_SENDER_ID = "776040776186";
	
	public static boolean isRunning = false;

	public Category mProductCategory;

	private MainActivity mContext;
	public SlidingMenu mLeftMenu;

	public FragmentManager mFragmentManager;
	public FragmentTransaction mFragmentTransaction;
	public int mScreenWidth, mScreenHeight;
	public Member mUser = null;
	public Order mOrder = null, mBuyNowOrder = null;
	private RelativeLayout mBtnBestOfToday, mBtnCategories, mBtnStyler, mBtnMyStyle, mBtnMyShopping, mBtnSetting;

	public MainPageView mMainPageView;

	public ArrayList<Product> mListProductBest = new ArrayList<Product>();
	public ArrayList<Product> mListProduct = new ArrayList<Product>();
	public ArrayList<Product> mListFavorite = new ArrayList<Product>();
	public ArrayList<Category> mCategories = new ArrayList<Category>();
	public ArrayList<Category> mFullCategories = new ArrayList<Category>();
	public ArrayList<Post> mListMyStyles = new ArrayList<Post>();
	public ArrayList<Post> mListAllStyle = new ArrayList<Post>();
	public ArrayList<Post> mListFollowStyle = new ArrayList<Post>();
	public ArrayList<City> mListCity = new ArrayList<City>();
	public ArrayList<District> mListDistrict = new ArrayList<District>();

	public ProgressDialog mLoadingDialog;
	private SharedPreferences mPrefs;
	private Uri mImageCaptureUri;
	public int mLastCartCount;
	public Boolean mEditedInfo = false, isConnectionErrorShow = false;
	public int mFirstStart = 0;

	public MainPageViewFragment mMainPageViewFragment;
	public ProductFragment mProductFragment;
	public FollowListFragment mFollowListFragment;
	public DetailFragment mDetailFragment;
	public StylerFragment mStylerFragment;
	public EditProfileFragment mEditProfileFragment;
	public MemberStyleFragment mMemberStyleFragment;

	public MyShoppingView mMyShoppingView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.w("Shopping", "Main onCreate");
		this.mContext = this;
		setContentView(R.layout.mainlayout);

		UrlImageViewHelper.setUseBitmapScaling(true);

		mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

		GetListCity();
		GetListDistrict();

		GetLastData();

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		mScreenWidth = metrics.widthPixels;
		mScreenHeight = metrics.heightPixels;

		LayoutInit();

		onNotificationArrived(getIntent());
	}

	private void LayoutInit() {

		mLoadingDialog = new ProgressDialog(this);
		mLoadingDialog.setCancelable(true);
		mLoadingDialog.setMessage(getString(R.string.loading));

		int menuWidth = mScreenWidth * 75 / 100;
		int numCol = (int) getResources().getDimension(R.dimen.grid_column);
		menuWidth = (numCol == 2 || mContext.mScreenWidth > 2000) ? 528 : menuWidth;
		// menuWidth = (menuWidth > 680) ? 680 : menuWidth;

		mLeftMenu = new SlidingMenu(mContext);
		mLeftMenu.setMode(SlidingMenu.LEFT);
		mLeftMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		mLeftMenu.setShadowWidth(15);
		mLeftMenu.setShadowDrawable(R.drawable.shadow);
		mLeftMenu.setBehindWidth(menuWidth);
		mLeftMenu.setFadeDegree(0.35f);
		mLeftMenu.attachToActivity(mContext, SlidingMenu.SLIDING_CONTENT);
		mLeftMenu.setMenu(R.layout.left_menu);

		mBtnBestOfToday = (RelativeLayout) findViewById(R.id.menu_btnBestOfToday);
		mBtnCategories = (RelativeLayout) findViewById(R.id.menu_btnCategories);
		mBtnMyShopping = (RelativeLayout) findViewById(R.id.menu_btnMyShopping);
		mBtnStyler = (RelativeLayout) findViewById(R.id.menu_btnStyler);
		mBtnMyStyle = (RelativeLayout) findViewById(R.id.menu_btnMyStyle);
		mBtnSetting = (RelativeLayout) findViewById(R.id.menu_btnSetting);

		// mBtnMenu.setOnClickListener(this);
		mBtnBestOfToday.setOnClickListener(this);
		mBtnCategories.setOnClickListener(this);
		mBtnStyler.setOnClickListener(this);
		mBtnMyStyle.setOnClickListener(this);
		mBtnMyShopping.setOnClickListener(this);
		mBtnSetting.setOnClickListener(this);
		// mBtnCart.setOnClickListener(this);

		mMainPageViewFragment = new MainPageViewFragment();
		mFragmentManager = mContext.getSupportFragmentManager();
		mFragmentTransaction = mFragmentManager.beginTransaction();
		mFragmentTransaction.add(R.id.main_layFragment, mMainPageViewFragment);
		mFragmentTransaction.commit();

	}

	// public void changeTitle(String title, boolean isStack) {
	// if (isStack)
	// mLastTitle = mTxtTitle.getText().toString();
	// Log.w("Shopping", "mLastTitle: " + mLastTitle);
	// Log.w("Shopping", "ChangeTitle: " + title);
	// mTxtTitle.setText(title);
	// }

	public void replaceFragment(Fragment fragment, boolean isBackStack) {
		if (fragment.isAdded())
			return;
		mFragmentTransaction = mFragmentManager.beginTransaction();
		if (mProductFragment != null && mProductFragment.isAdded()) {
			mFragmentTransaction.hide(mProductFragment);
			mFragmentTransaction.add(mProductFragment.getId(), fragment);
		} else if (mMemberStyleFragment != null && mMemberStyleFragment.isAdded()) {
			mFragmentTransaction.hide(mMemberStyleFragment);
			mFragmentTransaction.add(mMemberStyleFragment.getId(), fragment);
		} else if (mFollowListFragment != null && mFollowListFragment.isAdded()) {
			mFragmentTransaction.hide(mFollowListFragment);
			mFragmentTransaction.add(mFollowListFragment.getId(), fragment);
		} else {
			mFragmentTransaction.hide(mMainPageViewFragment);
			// if(!fragment.isAdded())
			mFragmentTransaction.add(R.id.main_layFragment, fragment);
		}
		if (isBackStack)
			// if(!fragment.isAdded())M
			mFragmentTransaction.addToBackStack(fragment.getTag());
		mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		mFragmentTransaction.commit();
	}

	public Locale getLocale() {
		return getResources().getConfiguration().locale;
	}

	public void AddPreference(String tag, String value) {
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putString(tag, value);
		editor.commit();
	}

	public String GetPreference(String tag) {
		return mPrefs.getString(tag, "");
	}

	public void AddPreferenceInt(String tag, int value) {
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putInt(tag, value);
		editor.commit();
	}

	public int GetPreferenceInt(String tag) {
		return mPrefs.getInt(tag, 0);
	}

	public void AddPreferenceBool(String tag, boolean value) {
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putBoolean(tag, value);
		editor.commit();
	}

	public boolean GetPreferenceBool(String tag) {
		return mPrefs.getBoolean(tag, true);
	}

	public void onLoginResult(Intent data) {
		final int result = data.getIntExtra("Id", -1);
		if (result != -1) {
			new CallServiceTask() {
				protected void onPreExecute() {
					// mMainPageView.mViewPager.setCurrentItem(0, false);
					mLoadingDialog.show();
				};

				private Member rs = null;

				public void work() {
					try {
						rs = service.getInfoMemberByID(result, -1);
						// rs.GCMID = GoogleCloudMessaging.getInstance(mContext)
						// .register(GCM_SENDER_ID);
						// service.updateGCMID(rs.Id, rs.GCMID);
					} catch (IOException e) {} catch (XmlPullParserException e) {}
				};

				protected void onPostExecute(Void result) {
					mLoadingDialog.dismiss();
					mContext.mUser = rs;
					mContext.mOrder = new Order();
					mMainPageView.mPageAdapter = new ViewPagerAdapter(mContext);
					// if (mFragmentManager.getBackStackEntryCount() > 0)
					// mLastTitle = getString(R.string.bestoftoday);
					// else
					// changeTitle(getString(R.string.bestoftoday), false);

					mMainPageView.mViewPager.setAdapter(mMainPageView.mPageAdapter);

					if (mUser != null) {
						AddPreference("User", ConvertToJson(mUser));
						((MyApplication) getApplicationContext()).startGCMNotification();
					} else {
						AddPreference("User", "");
					}
					int item = -1;
					if ((item = getIntent().getIntExtra("ReturnToTab", -1)) >= 0) {
						mMainPageView.mViewPager.setCurrentItem(item, false);
						getIntent().removeExtra("ReturnToTab");
					}
				};
			}.execute();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {

		if (requestCode == LOGINACTIVITY) {

			if (resultCode == RESULT_OK) {
				onLoginResult(data);
			}
			if (resultCode == RESULT_CANCELED) {
				// Write your code if there's no result

			}
		}

		if (requestCode == CROP_FROM_CAMERA) {
			if (resultCode == RESULT_OK) {
				final String path = data.getStringExtra(CropImage.IMAGE_PATH);
				new AsyncTask<Integer, Integer, Boolean>() {
					@Override
					protected Boolean doInBackground(Integer... params) {

						Utilities.createCropImage(path, IMAGE_TEMP);
						return null;
					}

					@Override
					protected void onPostExecute(Boolean result) {
						MyStyleView.mInstance.onActivityResult(IMAGE_TEMP);
					}
				}.execute();
			}
			if (resultCode == RESULT_CANCELED) {

			}
		}

		if (requestCode == CROP_EDIT_PROFILE) {
			if (resultCode == RESULT_OK) {
				final String path = data.getStringExtra(CropImage.IMAGE_PATH);
				new AsyncTask<Integer, Integer, Boolean>() {
					@Override
					protected Boolean doInBackground(Integer... params) {
						Utilities.createCropImage(path, IMAGE_TEMP);
						return null;
					}

					@Override
					protected void onPostExecute(Boolean result) {
						EditProfileView.mInstance.onActivityResult(IMAGE_TEMP);
					}
				}.execute();
			}
			if (resultCode == RESULT_CANCELED) {

			}
		}

		if (requestCode == CAMERA_MYSTYLE) {
			if (resultCode == RESULT_OK) {
				mImageCaptureUri = Uri.fromFile(new File(IMAGE_TEMP));
				runCropImage();
			}
			if (resultCode == RESULT_CANCELED) {

			}
		}

		if (requestCode == LIBRAR_MYSTYLE) {
			if (resultCode == RESULT_OK) {
				String path = getRealPathFromURI(data.getData());
				if (path == null) {
					Toast.makeText(mContext, mContext.getString(R.string.invalidimage), Toast.LENGTH_SHORT).show();
					return;
				}
				mImageCaptureUri = Uri.fromFile(new File(path));
				runCropImage();
			}
			if (resultCode == RESULT_CANCELED) {

			}
		}

		if (requestCode == LIBRAR_SETTING) {
			if (resultCode == RESULT_OK) {
				String path = getRealPathFromURI(data.getData());
				if (path == null) {
					Toast.makeText(mContext, mContext.getString(R.string.invalidimage), Toast.LENGTH_SHORT).show();
					return;
				}
				mImageCaptureUri = Uri.fromFile(new File(path));
				Intent intent = new Intent(this, CropImage.class);

				String filePath = mImageCaptureUri.getPath();
				Log.w("Shopping", "Path: " + filePath);

				intent.putExtra(CropImage.IMAGE_PATH, filePath);
				intent.putExtra(CropImage.SCALE, true);
				intent.putExtra(CropImage.ASPECT_X, 1);
				intent.putExtra(CropImage.ASPECT_Y, 1);

				startActivityForResult(intent, CROP_EDIT_PROFILE);
			}
			if (resultCode == RESULT_CANCELED) {

			}
		}

		if (requestCode == CAMERA_SETTING) {
			if (resultCode == RESULT_OK) {
				mImageCaptureUri = Uri.fromFile(new File(IMAGE_TEMP));
				Intent intent = new Intent(this, CropImage.class);

				String filePath = mImageCaptureUri.getPath();
				Log.w("Shopping", "Path: " + filePath);

				intent.putExtra(CropImage.IMAGE_PATH, filePath);
				intent.putExtra(CropImage.SCALE, true);
				intent.putExtra(CropImage.ASPECT_X, 1);
				intent.putExtra(CropImage.ASPECT_Y, 1);

				startActivityForResult(intent, CROP_EDIT_PROFILE);
			}
			if (resultCode == RESULT_CANCELED) {

			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public String getRealPathFromURI(Uri contentUri) {
		String path = null;
		String[] proj = { MediaStore.MediaColumns.DATA };
		Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
		if (cursor.moveToFirst()) {
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
			path = cursor.getString(column_index);
		}
		cursor.close();
		return path;
	}

	private void runCropImage() {

		Intent intent = new Intent(this, CropImage.class);

		String filePath = mImageCaptureUri.getPath();
		Log.w("Shopping", "Path: " + filePath);

		intent.putExtra(CropImage.IMAGE_PATH, filePath);
		intent.putExtra(CropImage.SCALE, true);
		intent.putExtra(CropImage.ASPECT_X, 0);
		intent.putExtra(CropImage.ASPECT_Y, 0);

		startActivityForResult(intent, CROP_FROM_CAMERA);
	}

	public void callMenu() {
		if (!mLeftMenu.isMenuShowing()) {
			mLeftMenu.showMenu();
		} else {
			mLeftMenu.showContent();
		}
	}

	public void callCart() {
		if (mUser == null) {
			Intent intent = new Intent(this, LoginActivity.class);
			startActivityForResult(intent, LOGINACTIVITY);
		} else {
			// mLastTitle = getString(R.string.myshopping);
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			mMainPageView.mViewPager.setCurrentItem(2, false);
			mMyShoppingView.showBuying();
		}
		mLeftMenu.showContent();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// case R.id.main_menu:
		// if (!mLeftMenu.isMenuShowing()) {
		// mLeftMenu.showMenu();
		// } else {
		// mLeftMenu.showContent();
		// }
		// break;
		case R.id.menu_btnBestOfToday:
			// mLastTitle = getString(R.string.bestoftoday);
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			mMainPageView.mViewPager.setCurrentItem(0, false);
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnCategories:
			// mLastTitle = getString(R.string.categories);
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			mMainPageView.mViewPager.setCurrentItem(1, false);
			// changeTitle(getString(R.string.categories), false);
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnMyShopping:
			if (mUser == null) {
				Intent intent = new Intent(this, LoginActivity.class);
				startActivityForResult(intent, LOGINACTIVITY);
			} else {
				// mLastTitle = getString(R.string.myshopping);
				if (mFragmentManager.getBackStackEntryCount() > 0) {
					for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
						mFragmentManager.popBackStack();
				}
				mMainPageView.mViewPager.setCurrentItem(2, false);
				// changeTitle(getString(R.string.myshopping), false);
			}
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnStyler:
			// mLastTitle = getString(R.string.styler);
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			if (mUser == null)
				mMainPageView.mViewPager.setCurrentItem(2, false);
			else
				mMainPageView.mViewPager.setCurrentItem(3, false);
			// changeTitle(getString(R.string.styler), false);
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnMyStyle:
			if (mUser == null) {
				Intent intent = new Intent(this, LoginActivity.class);
				startActivityForResult(intent, LOGINACTIVITY);
				getIntent().putExtra("ReturnToTab", 4);
			} else {
				// mLastTitle = getString(R.string.mystyle);
				if (mFragmentManager.getBackStackEntryCount() > 0) {
					for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
						mFragmentManager.popBackStack();
				}
				mMainPageView.mViewPager.setCurrentItem(4, false);
			}
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnSetting:
			// mLastTitle = getString(R.string.setting);
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			if (mUser == null)
				mMainPageView.mViewPager.setCurrentItem(3, false);
			else
				mMainPageView.mViewPager.setCurrentItem(5, false);
			mLeftMenu.showContent();
			break;

		// case R.id.main_cart:
		// if (mUser == null) {
		// Intent intent = new Intent(this, LoginActivity.class);
		// startActivityForResult(intent, LOGINACTIVITY);
		// } else {
		// mLastTitle = getString(R.string.myshopping);
		// if (mFragmentManager.getBackStackEntryCount() > 0) {
		// for (int i = 0; i < mFragmentManager
		// .getBackStackEntryCount(); i++)
		// mFragmentManager.popBackStack();
		// }
		// mMainPageView.mViewPager.setCurrentItem(2, false);
		// mMyShoppingView.showBuying();
		// }
		// mLeftMenu.showContent();
		// break;
		}
	}

	public void GetListCity() {
		new CallServiceTask() {
			private ArrayList<City> rs = new ArrayList<City>();

			public void work() {
				try {
					rs = service.getListCity();
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				mListCity.addAll(rs);
			};
		}.execute();
	}

	public void GetListDistrict() {
		new CallServiceTask() {
			private ArrayList<District> rs = new ArrayList<District>();

			public void work() {
				try {
					rs = service.getListDistrict();
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				mListDistrict.addAll(rs);
			};
		}.execute();
	}

	private boolean isBack = false;

	@Override
	public void onLowMemory() {
		super.onLowMemory();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		((MyApplication) getApplicationContext()).mBadge.hideBadge();
		isRunning = true;
	}

	@Override
	public void onBackPressed() {
		if (mLeftMenu.isMenuShowing()) {
			mLeftMenu.showContent();
		} else if (mFragmentManager.getBackStackEntryCount() > 0)
			if (mDetailFragment != null && mDetailFragment.isAdded()) {
				if (mDetailFragment.view != null && mDetailFragment.view.PopBack()) {
					Back();
				}
			} else
				Back();
		else {
			if (isBack) {
				Back();
			} else {
				if (mMainPageView.mViewPager.getCurrentItem() != 0)
					mMainPageView.mViewPager.setCurrentItem(0, false);
				else {
					isBack = true;
					Timer timer = new Timer();
					timer.schedule(new TimerTask() {
						@Override
						public void run() {
							isBack = false;
						}
					}, 2000);
					Toast.makeText(mContext, getString(R.string.backexit), Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	public void Back() {
		super.onBackPressed();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			if (!mLeftMenu.isMenuShowing()) {
				mLeftMenu.showMenu();
			} else {
				mLeftMenu.showContent();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	void GetLastData() {
		Gson gson = new Gson();
		mOrder = new Order();
		// mStartedPos = GetPreferenceInt("ViewState");
		String order = GetPreference("Order");
		if (!order.equals("")) {
			mOrder.ListDetail = gson.fromJson(order, new TypeToken<ArrayList<OrderDetail>>() {}.getType());
		}

		String user = GetPreference("User");
		if (!user.equals("")) {
			mUser = gson.fromJson(user, Member.class);
			if (GetPreferenceBool("GetNotification"))
				((MyApplication) getApplicationContext()).startGCMNotification();
		}

		String best = GetPreference("ListProductBest");
		if (!best.equals("")) {
			mListProductBest = gson.fromJson(best, new TypeToken<ArrayList<Product>>() {}.getType());
		}

	}

	public String ConvertToJson(Object O) {
		Gson gson = new Gson();
		return gson.toJson(O);
	}

	@Override
	protected void onStop() {
		// AddPreferenceInt("ViewState",
		// mMainPageView.mViewPager.getCurrentItem());
		Log.w("Shopping", "onStop");
		super.onStop();
		isRunning = false;
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.w("MainActivity", "onResume");
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		// onNotificationArrived(getIntent());
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Log.w("Shopping", "onAttachedToWindow");
		mFirstStart = GetPreferenceInt("FirstStart");
		Log.w("Shopping", "mFirstStart = " + mFirstStart);
		if (mFirstStart != 0) {
			AddPreferenceInt("FirstStart", 0);
			Intent intent = new Intent(mContext, MainActivity.class);
			if (getIntent().getExtras() != null) {
				String notiExtras = getIntent().getExtras().getString(GCMIntentService.DATA_TAG, "");
				if (!notiExtras.equals(""))
					intent.putExtra(GCMIntentService.DATA_TAG, notiExtras);
			}
			mContext.startActivity(intent);
			mContext.finish();
		} else {
			mFirstStart = 1;
			AddPreferenceInt("FirstStart", mFirstStart);
			Log.w("Shopping", "mFirstStart = " + mFirstStart);
		}
	}

	public void SaveListBestToCache() {
		if (mListProductBest.size() != 0) {
			AddPreference("ListProductBest", ConvertToJson(mListProductBest));
		} else {
			AddPreference("ListProductBest", "");
		}
	}

	@Override
	protected void onDestroy() {
		Log.w("Shopping", "onDestroy");
		AddPreferenceInt("FirstStart", 0);
		AddPreferenceInt("ViewState", 0);
		if (mOrder != null) {
			AddPreference("Order", ConvertToJson(mOrder.ListDetail));
		} else {
			AddPreference("Order", "");
		}
		if (mUser != null) {
			AddPreference("User", ConvertToJson(mUser));
		} else {
			AddPreference("User", "");
		}
		if (mListProductBest.size() != 0) {
			AddPreference("ListProductBest", ConvertToJson(mListProductBest));
		} else {
			AddPreference("ListProductBest", "");
		}
		super.onDestroy();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Log.w("Push Notification", "onNewIntent");
		super.onNewIntent(intent);
		onNotificationArrived(intent);
	}

	private void onNotificationArrived(Intent intent) {
		Bundle extras = intent.getExtras();
		if (extras != null && extras.containsKey(GCMIntentService.DATA_TAG) && !extras.getString(GCMIntentService.DATA_TAG).equals("")) {
			Log.w("Push Notification", "has " + GCMIntentService.DATA_TAG + " extra");
			((MyApplication) getApplicationContext()).mBadge.hideBadge();
			final Notify noti = new Gson().fromJson(extras.getString(GCMIntentService.DATA_TAG), Notify.class);
			if (noti.CommentType == 1) {
				if (mDetailFragment == null)
					mDetailFragment = new DetailFragment();
				if (!mDetailFragment.isAdded()) {
					mDetailFragment.setProductID(noti.PostID);
					replaceFragment(mDetailFragment, true);
				}
			}
			if (noti.CommentType == 2) {
				final boolean myStyle = (mUser != null && mUser.Id == noti.MemID);
				if (mContext.mStylerFragment == null)
					mContext.mStylerFragment = new StylerFragment();
				if (!mContext.mStylerFragment.isAdded()) {
					mContext.mStylerFragment.setPostID(noti.PostID, myStyle);
					mContext.replaceFragment(mContext.mStylerFragment, true);
				}
			}
			// intent.removeExtra(GCMIntentService.DATA_TAG);
			GCMIntentService.NUMBER = 0;
		}
	}
}
